/**
 * Copyright 2005 WUZEWEN. All rights reserved.
 * WZW PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.kingcore.pda.database.controller;


/**
 * <p>获取提交的sql语句并且执行。
 *		数据库连接：根据提交的项目编号得到相应的连接池；
 *		sql语句群：表单对象的值，如：delete ...; insert ....; update ....;
 *						各单一的sql语句之间使用;号分隔。</p>
 * @author	WUZEWEN on 2005-11-14
 * @version	1.0
 * @see		Object#equals(java.lang.Object)
 * @see		Object#hashCode()
 * @see		HashMap
 * @since	JDK5
 */

                 
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.kingcore.framework.context.ApplicationContext;
import com.kingcore.framework.util.StringUtils;
import com.kingcore.pda.base.controller.PdaAction;


public class ExecuteSqlStatementAction extends PdaAction {
	
    
    public ActionForward executeAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException{
		// 类成员 {
		// 类成员
		String dbType = "" ;	//数据库类型
		String driver = "" ;	//驱动类
		String url = "" ;		//连接url属性
		String username="";		
		String password="";
		String maxconn="";		//最大连接数
		String path="" ;		//导出的sql文件存放路径
		String tableCondition="";	//表的特征条件
		String is_tblname="";	//表名
		String poolName="";		//连接池名字

		clearErrors();
		//copyright protect here
		String serverLoginName=System.getProperty("user.name");
		if(!( serverLoginName.equalsIgnoreCase("WUZEWEN")
		    ||serverLoginName.equalsIgnoreCase("WZWEN")
		    ||serverLoginName.equalsIgnoreCase("Zewin")
		    ||serverLoginName.equalsIgnoreCase("Zeven")
		    ||serverLoginName.equalsIgnoreCase("Administrator") )){

			addErrors("err.illegalAuthorization");
			this.saveError(request);
			return mapping.findForward("fail");	
		}

		//获取配置文件值
		java.util.Properties pro=new java.util.Properties();
		try
		{			
			pro.load(new java.io.FileInputStream(request.getRealPath("")+"/WEB-INF/conf/pda-project.properties"));
			String conf_prefix=null;
			conf_prefix=request.getParameter("projectCode");	//从客户端取编号
			//System.out.println ("aa"+conf_prefix);
			if(conf_prefix==null || conf_prefix.trim().equals("null") || conf_prefix.trim().equals("")){
				//System.out.println ("faddd");
				conf_prefix=pro.getProperty("use-config");
			}else{
				//conf_prefix=conf_prefix.substring( 0, conf_prefix.indexOf("_") );
			}
			
			conf_prefix=(conf_prefix==null)?"":(conf_prefix+".");
			//System.out.println (conf_prefix);
			dbType=pro.getProperty( conf_prefix+"dbType");
			poolName=pro.getProperty( conf_prefix+"poolName");
			tableCondition=pro.getProperty( conf_prefix+"tableCondition");
			path=pro.getProperty( conf_prefix+"expPath");
			
			if(tableCondition==null || tableCondition.trim().equals("")){
				tableCondition="1=1" ;
			}
		}catch(java.io.IOException e){
			System.out.println ("cann't load properties.properties file"+e.getMessage());
			return mapping.findForward("success");
		}
		
		//创建数据库连接并且获取信息
		String sql,sqlall;
		Connection conn = null ;
		Statement  stmt  = null ;
		Statement  stmt2  = null ;
		ResultSet  rs =null;
		ResultSetMetaData rsmd=null;
		int loops = 0 ;
		try{
			//得到数据库连接
			//Class.forName(driver) ;
			//conn = DriverManager.getConnection(url, username, password) ;
			conn=ApplicationContext.getInstance().getDataSourceManager().getConnection(poolName);
			//if( testResultSet(conn) ) return ;	
			stmt=conn.createStatement();
			stmt2=conn.createStatement();
			//System.out.println("dfljshfjksfkl" + sql);
			
			sqlall=request.getParameter("sqlall");
			System.out.println ("sql1="+sqlall);
			//System.out.println ("sql===========");
			sqlall=sqlall.trim();
			if(!sqlall.endsWith(";")){
				sqlall+=";";
			}
			int i=0,j=0;
			i=sqlall.indexOf(";");
			String sql_1="";
			while(i>0){
				sql_1=StringUtils.toGB2312(sqlall.substring(j,i));
				if(sql_1.indexOf("drop")>=0){
					stmt2.addBatch(sql_1);		//这个是可以出错的sql集合
				}else{
					stmt.addBatch(sql_1);
				}
				System.out.println ("one=" + sql_1);
				i++;
				j=i;
				i=sqlall.indexOf(";",j);
			}
			try{
				stmt2.executeBatch();
				conn.commit();
			}catch(Exception e){
				System.out.println ("出现允许的错误，"+e.getMessage());
			}
			
			stmt.executeBatch();
			conn.commit();
			this.addErrors("msg.execsqlsuccess");
			this.saveError(request);		
			return mapping.findForward("success");
			
		}catch(Exception e){
			System.out.println ("处理产生错误：" + e.getMessage());
			this.addErrors("msg.execsqlfail---");
			this.addErrors("msg.execsqlfail");
			System.out.println ("execute sql error");
			throw new ServletException("处理产生错误：" + e.getMessage());
			//this.saveError(request);
			//return mapping.findForward("fail");
		}finally{
			try{
				if(rs!=null)
					rs.close();
				if(stmt!=null)
					stmt.close();
				if(conn!=null)
					conn.close();
			}catch(java.sql.SQLException e){
				throw new ServletException ("error when close rs and stmt");
			}
		}
			
	}
}
